package com.terios.logic;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;

import com.terios.Paging;
import com.terios.Status;
import com.terios.User;
import com.terios.conts.CommonStrs;
import com.terios.http.WeiboResponse;
import com.terios.intfs.IWeiboActivity;
import com.terios.logic.ui.HomeActivity;
import com.terios.logic.ui.LoginActivity;
import com.terios.logic.ui.MainActivity;
import com.weibo.net.AccessToken;
import com.weibo.net.Weibo;
import com.weibo.net.WeiboException;
import com.weibo.net.WeiboParameters;

/**
 * MainService.java 2012-9-27 下午12:14:11
 * 
 * @author Wang Tengrui (核心控制类) 完成程序调度 接收UI层数据(任务)，完成业务逻辑，返回信息，更新UI
 *         在后台运行(继承自Service类) 线程(实现Runnable接口) 不断侦听UI传过来任务消息
 */
public class MainService extends Service implements Runnable
{
	public static Weibo weibo;
	public static User nowUser;// 当前用户

	// 把Activity添加到allActivity数组列表中，以便管理和调用
	public static ArrayList<Activity> allActivity = new ArrayList<Activity>();

	// 将所有任务添加到allTask数组列表中，以便管理和调用
	public static ArrayList<Task> allTask = new ArrayList<Task>();

	// 遍历查找需要的Activity
	public static Activity getActivityByName(String name)
	{
		for (Activity activity : allActivity)
		{
			if (activity.getClass().getName().indexOf(name) >= 0)
			{
				Log.i("status", ACTIVITY_SERVICE.getClass().getName()
						.toString());
				return activity;
			}
		}
		return null;
	}

	// 添加Task到数组列表中
	public static void addTask(Task task)
	{
		allTask.add(task);
	}

	public boolean isRun = true;// 线程开关

	private Handler handler = new Handler()
	{

		@Override
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			switch (msg.what)
			{
			case CommonStrs.TASK_USER_LOGIN:// 通知Login页面 登陆成功
				IWeiboActivity loginActivity = (IWeiboActivity) MainService
						.getActivityByName(LoginActivity.getMyName(false));// 获得Activity
				loginActivity.refresh(
						Integer.valueOf(LoginActivity.REFRESH_LOGIN), msg.obj);// 调用Login
																				// Activity刷新页面的方法
																				// 注：Integer（）和Integer.valueOf（）的区别
				break;
			case CommonStrs.TASK_GET_USER_HOMETIMEINLINE:// 获取主页内容
				IWeiboActivity homeActivity = (IWeiboActivity) MainService
						.getActivityByName(HomeActivity.getMyName(false));
				homeActivity.refresh(MainActivity.REFRESH_WEIBO, msg.obj);
				break;
			case CommonStrs.TASK_SEARCH_WEIBO:
				/*
				 * IWeiboActivity searchActivity =
				 * (IWeiboActivity)MainService.getActivityByName
				 * ("SearchActivity");
				 * searchActivity.refresh(SearchActivity.SEARCH_WEIBO,msg.obj);
				 */
				break;
			}
		}

	};

	private void doTask(Task task)
	{
		Message message = handler.obtainMessage();
		message.what = task.getTaskID();
		switch (task.getTaskID())
		{
		case CommonStrs.TASK_USER_LOGIN:// 执行登录任务
			String token = (String) task.getTaskParam().get("token");
			String secret = CommonStrs.CONSUMER_SECRET;
			AccessToken accessToken = new AccessToken(token, secret);
			weibo = Weibo.getInstance();
			weibo.setAccessToken(accessToken);
			Log.i("accessToken", weibo.getAccessToken().getToken());
			WeiboParameters bundle1 = new WeiboParameters();
			bundle1.add("uid", (String)task.getTaskParam().get("uid"));
			WeiboResponse mWeiboResponse1 = WeiboResponse.getInstance(getActivityByName("LoginActivity"));
			try {
				nowUser = new User(mWeiboResponse1.getUserInfo(bundle1));
			} catch (WeiboException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
			message.obj = nowUser;

			break;
		case CommonStrs.TASK_GET_USER_HOMETIMEINLINE:// 得到刷新主页面信息的任务
			// HomeActivity传递来的分页参数
			Paging paging = new Paging((Integer) task.getTaskParam().get(
					"nowPage"), (Integer) task.getTaskParam().get("pageSize"));
			WeiboParameters bundle2 = new WeiboParameters();
			bundle2.add("source", Weibo.getAppKey());
			bundle2.add("page", String.valueOf(paging.getPage()));
			bundle2.add("count", String.valueOf(paging.getCount()));
			List<Status> allWeibo = null;
			WeiboResponse mWeiboResponse2 = WeiboResponse.getInstance(getActivityByName("HomeActivity"));
			try
			{
				allWeibo = Status.statusList(mWeiboResponse2.getHomeTimeLine(bundle2));
				message.obj = allWeibo;
			} catch (WeiboException e)
			{
				Log.e("MainService","获取当前登录用户及其所关注用户的最新微博 失败");
				e.printStackTrace();
			}
			break;
		case CommonStrs.TASK_SEARCH_WEIBO:// 搜索微博

			break;
		}
		handler.sendMessage(message);// 发送消息
		allTask.remove(task);// 任务处理完毕，移除该任务
	}

	@Override
	public void onCreate()
	{
		super.onCreate();
		isRun = true;// 启动线程
		Thread thread = new Thread(this);
		thread.start();
	}

	@Override
	public void onDestroy()
	{
		super.onDestroy();
		this.stopSelf();
		isRun = false;
	}

	@Override
	public void run()
	{
		while (isRun)
		{
			Task lastTask = null;
			synchronized (allTask)
			{
				if (allTask.size() > 0)
				{
					lastTask = allTask.get(0);
					doTask(lastTask);
				}
			}
			// 每隔一秒侦查是否是否还有任务
			try
			{
				Thread.sleep(1000);
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}
		}
	}

	@Override
	public IBinder onBind(Intent intent)
	{
		return null;
	}

	/**
	 * 退出应用
	 */
	public static void exitApp(Context context)
	{
		context.stopService(new Intent("com.terios.logic.MainService"));//停止主服务
		android.os.Process.killProcess(android.os.Process.myPid());
		for (Activity activity : allActivity)
		{
			activity.finish();
		}
	}

	/**
	 * 网络连接异常 按钮显示信息未定义
	 */
	public static void alertNetError(final Context context)
	{
		AlertDialog.Builder alertError = new AlertDialog.Builder(context);
		alertError.setTitle("");
		alertError.setMessage("");
		alertError.setNegativeButton("", new OnClickListener()
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				exitApp(context);
			}
		});
		alertError.setPositiveButton("", new OnClickListener()
		{

			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				dialog.dismiss();
				context.startActivity(new Intent(
						android.provider.Settings.ACTION_WIRELESS_SETTINGS));
			}
		});
		alertError.create().show();

	}
}
